package com.whzykj.resource;

import java.math.BigDecimal;
import java.util.List;

import net.sf.json.JSONObject;

import com.google.common.collect.Lists;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.JsonUtil;
import com.whzykj.common.ReturnEnum;
import com.whzykj.model.Dictionary;
import com.whzykj.model.LogLoginStatus;
import com.whzykj.model.RechargeActivityDetails;
import com.whzykj.model.Station;
import com.whzykj.model.Userinfo;

public class BaseResource {

	/**
	 * 登录
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'login',username:'18627764533',password:'91b8012cfed6d6025dabb43c9be019c9'
	 *            }
	 * 
	 */
	public void login(JSONObject messageObj, JSONObject result) {
		String username = messageObj.getString("username");// 手机号
		boolean flag = CommonUtils.isMobileNO(username);
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT * FROM userinfo WHERE ENABLE=1 ");
		if (flag) {
			sbf.append(" AND mobile=? ");
		} else {
			sbf.append(" AND username=? ");
		}
		Object password = messageObj.get("password");// 密码
		// Object rand = messageObj.get("rand");//验证码
		Record userInfo = Db.findFirst(sbf.toString(), username);
		// 1：判断数据库中是否存在该用户
		if (userInfo == null) {
			JsonUtil.put(result, ReturnEnum.NO_REGISTER);
			return;
		}

		// 2:判断该用户的角色是否为小B，不是则返回
		int role = userInfo.getInt("role");
		if (role != 5) {
			JsonUtil.put(result, ReturnEnum.USER_ROLE_FAIL);
			return;
		}

		// 3：判断小B客户的站点通用密码
		String login_password = userInfo.getStr("password");
		int custid = userInfo.getInt("cust_id");
		String sql = " SELECT * FROM customer WHERE is_valid=1 AND cust_id=? ";
		Record cust = Db.findFirst(sql, custid);
		int stationid = cust.getInt("station_id");
		Station station = Station.dao.findById(stationid);
		String station_password = "";
		boolean isLogin = false;
		if (station != null) {
			station_password = station.getStr("station_password");
			if (station_password.equals(password.toString())) {
				isLogin = true;
			}
		}

		// 4：根据站点通用密码是否正确判断是否需要判断小B的登录密码
		if (isLogin) {
			result.putAll(JsonUtil.getMapByJfinalRecord(cust));
			JsonUtil.put(result, ReturnEnum.LOGIN_SUCCESS);
			result.putAll(JsonUtil.getMapByJfinalRecord(userInfo));
		} else {
			if (!login_password.equals(password.toString())) {
				JsonUtil.put(result, ReturnEnum.LOGIN_FAIL);
				return;
			}
			result.putAll(JsonUtil.getMapByJfinalRecord(cust));
			JsonUtil.put(result, ReturnEnum.LOGIN_SUCCESS);
			result.putAll(JsonUtil.getMapByJfinalRecord(userInfo));
		}
	}

	/**
	 * 登录
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'nlogin',username:'18627764533',password:'91b8012cfed6d6025dabb43c9be019c9',equipid:'91b8012cfed',equipkind:'ios|android'
	 *            }
	 * 
	 */
	public void nlogin(JSONObject messageObj, JSONObject result) {
		String username = messageObj.getString("username");// 手机号
		boolean flag = CommonUtils.isMobileNO(username);
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT * FROM userinfo WHERE ENABLE=1 ");
		if (flag) {
			sbf.append(" AND mobile=? ");
		} else {
			sbf.append(" AND username=? ");
		}
		Object password = messageObj.get("password");// 密码
		// Object rand = messageObj.get("rand");//验证码
		Record userInfo = Db.findFirst(sbf.toString(), username);
		// 1：判断数据库中是否存在该用户
		if (userInfo == null) {
			JsonUtil.put(result, ReturnEnum.NO_REGISTER);
			return;
		}

		// 2:判断该用户的角色是否为小B，不是则返回
		int role = userInfo.getInt("role");
		if (role != 5) {
			JsonUtil.put(result, ReturnEnum.USER_ROLE_FAIL);
			return;
		}

		// 3：判断小B客户的站点通用密码
		String login_password = userInfo.getStr("password");
		int custid = userInfo.getInt("cust_id");
		String sql = " SELECT * FROM customer WHERE is_valid=1 AND cust_id=? ";
		Record cust = Db.findFirst(sql, custid);
		int stationid = cust.getInt("station_id");
		Station station = Station.dao.findById(stationid);
		String station_password = "";
		boolean isLogin = false;
		if (station != null) {
			station_password = station.getStr("station_password");
			if (station_password.equals(password.toString())) {
				isLogin = true;
			}
		}

		// 4：根据站点通用密码是否正确判断是否需要判断小B的登录密码
		String equipid = messageObj.getString("equipid");
		String equipkind = messageObj.getString("equipkind");
		if (isLogin) {
			String remarks = "站长通用密码登录";
			LogLoginStatus.dao.log(userInfo, equipid, equipkind, remarks, 1);
			result.putAll(JsonUtil.getMapByJfinalRecord(cust));
			JsonUtil.put(result, ReturnEnum.LOGIN_SUCCESS);
			result.putAll(JsonUtil.getMapByJfinalRecord(userInfo));
		} else {
			if (!login_password.equals(password.toString())) {
				JsonUtil.put(result, ReturnEnum.LOGIN_FAIL);
				return;
			}
			String remarks = "客户自身密码登录";
			LogLoginStatus.dao.log(userInfo, equipid, equipkind, remarks, 1);
			result.putAll(JsonUtil.getMapByJfinalRecord(cust));
			JsonUtil.put(result, ReturnEnum.LOGIN_SUCCESS);
			result.putAll(JsonUtil.getMapByJfinalRecord(userInfo));
		}
	}

	/**
	 * APP用户退出登录
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'logout',username:'18627764533',equipid:'91b8012cfed',equipkind:'ios|android'
	 *            }
	 */
	public void logout(JSONObject messageObj, JSONObject result) {
		String username = messageObj.getString("username");// 手机号
		boolean flag = CommonUtils.isMobileNO(username);
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT * FROM userinfo WHERE ENABLE=1 ");
		if (flag) {
			sbf.append(" AND mobile=? ");
		} else {
			sbf.append(" AND username=? ");
		}
		Record userInfo = Db.findFirst(sbf.toString(), username);
		// 1：判断数据库中是否存在该用户
		if (userInfo == null) {
			JsonUtil.put(result, ReturnEnum.LOGOUT_SUCCESS);
			return;
		}
		String equipid = messageObj.getString("equipid");
		String equipkind = messageObj.getString("equipkind");
		LogLoginStatus.dao.log(userInfo, equipid, equipkind, "退出登录", 0);
		JsonUtil.put(result, ReturnEnum.LOGOUT_SUCCESS);
	}

	/**
	 * 蔬菜类型接口
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'dic',dictype:'GOODS_KIND'}
	 */
	public void dic(JSONObject messageObj, JSONObject result) {
		Object dictype = messageObj.get("dictype");// 密码
		List<Dictionary> dicList = Dictionary.me.getDic(dictype.toString());
		result.put("data", JsonKit.toJson(dicList));
		JsonUtil.put(result, ReturnEnum.DIC_LIST_SUCCESS);
	}

	/**
	 * 公告接口
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'notice'}
	 */
	public void notice(JSONObject messageObj, JSONObject result) {
		String sql = " SELECT * FROM notice WHERE NOW() BETWEEN start_date AND end_date ORDER BY notice_id DESC ";
		result.put("data", JsonKit.toJson(Db.find(sql)));
		JsonUtil.put(result, ReturnEnum.DIC_LIST_SUCCESS);
	}

	/**
	 * 公告接口
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'appversion'}
	 */
	public void appversion(JSONObject messageObj, JSONObject result) {
		String sql = " SELECT * FROM appversion WHERE state='1' ORDER BY create_time DESC ";
		result.put("data", JsonKit.toJson(Db.find(sql)));
		JsonUtil.put(result, ReturnEnum.APPVERSION_SUCCESS);
	}
	
	/**
	 * app 配置文件，判断app是调用测试环境(0)、发布环境(1)、生产环境(2)
	 * @param messageObj
	 * @param result
	 * http://localhost:8080/bcy/mobile/Interface?content={namespace:'base',type:'appversion',appkind:'0'}
	 */
//	public void appconfig(JSONObject messageObj, JSONObject result){
//		String appkind=messageObj.getString("appkind");		// 获取APP的类型：0-测试环境；1-发布环境；2-生产环境
//	}

	/**
	 * 登录
	 * 
	 * @param messageObj
	 * @param result
	 *            http://localhost:8080/bcy/mobile/Interface?content={namespace:
	 *            'base',type:'modifypwd',userid:'13',password:'a0c4f24a940e2fe01cafb2ec60d51d6c',newpassword:'123'
	 *            }
	 */
	public void modifypwd(JSONObject messageObj, JSONObject result) {
		String userid = messageObj.getString("userid");// 手机号
		StringBuffer sbf = new StringBuffer();
		sbf.append(" SELECT * FROM userinfo WHERE userid=? ");
		Object password = messageObj.get("password");// 密码
		Record userInfo = Db.findFirst(sbf.toString(), userid);
		if (userInfo == null) {
			JsonUtil.put(result, ReturnEnum.NO_REGISTER);
			return;
		}
		String login_password = userInfo.getStr("password");
		if (!login_password.equals(password.toString())) {
			JsonUtil.put(result, ReturnEnum.LOGIN_FAIL);
			return;
		}

		Object newpassword = messageObj.get("newpassword");// 密码

		String sql = " update userinfo set password=? where userid=? ";
		int count = Db.update(sql, newpassword, userid);
		if (count == 0) {
			JsonUtil.put(result, ReturnEnum.MODIFY_PWD_FAIL);
			return;
		}
		JsonUtil.put(result, ReturnEnum.MODIFY_PWD_SUCCESS);
	}
	
	/**
	 * 查询充值活动
	 * @param messageObj
	 * @param result
	 *       http://localhost:8080/bcy/mobile/Interface?content={namespace:'base',type:'activitydetails',userid:''}
	 */
	public void activitydetails(JSONObject messageObj, JSONObject result) {
		
		String userid = messageObj.getString("userid");//
		Record rd = Userinfo.dao.getUserInfo(userid);
		int stationid = rd.getInt("station_id");
		List<RechargeActivityDetails> rdList =RechargeActivityDetails.me.findValidRechargeActivityDetailsList(stationid);
		if (rdList.size() == 0) {
			JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS_NODATA);
			return;
		}
		result.put("data", JsonKit.toJson(rdList));
		JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS);
	}
	
	/**
	 * 根据传入的站点ID查找对应的线上充值活动最大金额
	 * @param messageObj
	 * @param result
	 *       http://localhost:8080/bcy/mobile/Interface?content={namespace:'base',type:'maxamountonline',userid:''}
	 */
	public void maxamountonline(JSONObject messageObj, JSONObject result) {
		
		String userid = messageObj.getString("userid");//
		Record rd = Userinfo.dao.getUserInfo(userid);
		int stationid = rd.getInt("station_id");
		BigDecimal amount =RechargeActivityDetails.me.getMaxActivityAmountOnline(stationid);
		result.put("maxamount", amount.toString()+"元");
		JsonUtil.put(result, ReturnEnum.RETURN_SUCCESS);
	}

}
